package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.bean.UserLoginBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/3/18 10:43
 */
public class Dws_04_DwsUserUserLoginWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindow().init(
            4004,
            2,
            "Dws_04_DwsUserUserLoginWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 过滤用户登录记录
        SingleOutputStreamOperator<JSONObject> loginStream = filterLoginLog(stream);
        //2. 再去找到每个用户当日的第一次登录
        //        判断是否为 7 日回流
        SingleOutputStreamOperator<UserLoginBean> beanStream = parseToPojo(loginStream);
        
        //        3. 开窗聚合
        //            windowAll
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanStream);
    
        //        4.  写出
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window", UserLoginBean.class));
    }
    
    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> beanStream) {
      return  beanStream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean value1,
                                                UserLoginBean value2) throws Exception {
                        
                        value1.setBackCt(value1.getBackCt() + value2.getBackCt()) ;
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt()); ;
                        return value1;
                    }
                },
                new AllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<UserLoginBean> values,
                                      Collector<UserLoginBean> out) throws Exception {
                        UserLoginBean bean = values.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(window.getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(window.getEnd()));
    
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<UserLoginBean> parseToPojo(SingleOutputStreamOperator<JSONObject> loginStream) {
        return loginStream
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                
                private ValueState<String> lastLoginDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDate", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
                    
                    String lastLoginDate = lastLoginDateState.value();
                    
                    Long uuCt = 0L;
                    Long backCt = 0L;
                    if (!today.equals(lastLoginDate)) {
                        // 今天的首次登录
                        uuCt = 1L;
                        lastLoginDateState.update(today);
                        
                        // 当是今天的首次登录, 并且曾经登录过, 的时候, 判断下是否为 7 日回流用户
                        if (lastLoginDate != null) {
                            if ((ts - AtguiguUtil.dateToTs(lastLoginDate)) / 1000 / 60 / 60 / 24 >= 7) {
                                backCt = 1L;
                            }
                        }
                    }
                    if (uuCt == 1) {
                        out.collect(new UserLoginBean("", "", backCt, uuCt, ts));
                    }
                    
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> filterLoginLog(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
                    .withIdleness(Duration.ofSeconds(60))
            )
            .filter(new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject obj) throws Exception {
                    String lastPageId = obj.getJSONObject("page").getString("last_page_id");
                    String uid = obj.getJSONObject("common").getString("uid");
                    return (lastPageId == null || "login".equals(lastPageId)) && uid != null;
                }
            });
    }
}
/*
用户域用户登录各窗口汇总表
从 Kafka 页面日志主题读取数据，统计七日回流用户和当日独立用户数

当日独立用户数
    有多少个不同的用户登录

七日回流用户
    最后一次登录是 7 天前, 并且今天也登录了

1. 过滤用户登录记录
    找到用户的登录记录
    
    页面日志
        自动登陆
            last_page_id = null && uid != null
        
        手动登陆
            页面 A -> 登陆页 -> 页面 A/B(√)
            
            last_page_id=login && uid != null
            
         合并:
         (last_page_id = null || last_page_id=login) && uid != null
         
         
    
2. 再去找到每个用户当日的第一次登录
        判断是否为 7 日回流

3. 开窗聚合
    windowAll

4.  写出


 */